#!/bin/bash
## kola:
##   exclusive: false
##   description: Verify that there are no file/directory with
##     SetUID bit set, except the known files and directories.

set -xeuo pipefail

# shellcheck disable=SC1091
. "$KOLA_EXT_DATA/commonlib.sh"

# List of known files and directories with SetUID bit set
list_setuid_files=(
    '/usr/bin/chage'
    '/usr/bin/chfn'
    '/usr/bin/chsh'
    '/usr/bin/fusermount'
    '/usr/bin/fusermount3'
    '/usr/bin/gpasswd'
    '/usr/bin/mount'
    '/usr/bin/newgrp'
    '/usr/bin/passwd'
    '/usr/bin/pkexec'
    '/usr/bin/su'
    '/usr/bin/sudo'
    '/usr/bin/umount'
    '/usr/lib/polkit-1/polkit-agent-helper-1'
    '/usr/libexec/openssh/ssh-keysign'
    '/usr/sbin/grub2-set-bootflag'
    '/usr/sbin/mount.nfs'
    '/usr/sbin/pam_timestamp_check'
    '/usr/sbin/unix_chkpwd'
)

# List of known files and directories with SetUID bit set (RHCOS only)
list_setuid_files_rhcos=(
    '/usr/libexec/dbus-1/dbus-daemon-launch-helper'
    '/usr/libexec/sssd/krb5_child'
    '/usr/libexec/sssd/ldap_child'
    '/usr/libexec/sssd/proxy_child'
    '/usr/libexec/sssd/selinux_child'
)

is_fcos="false"
if [[ "$(source /etc/os-release && echo "${ID}")" == "fedora" ]]; then
    is_fcos="true"
fi

unknown_setuid_files=""
while IFS= read -r -d '' e; do
    found="false"
    for k in "${list_setuid_files[@]}"; do
        if [[ "${k}" == "${e}" ]]; then
            found="true"
            break
        fi
    done
    if [[ "${is_fcos}" == "false" ]]; then
        for k in "${list_setuid_files_rhcos[@]}"; do
            if [[ "${k}" == "${e}" ]]; then
                found="true"
                break
            fi
        done
    fi
    if [[ "${found}" == "false" ]]; then
        unknown_setuid_files+=" ${e}"
    fi
done< <(find /usr /etc -type f -perm /4000 -print0 -o -type d -perm /4000 -print0)

if [[ -n "${unknown_setuid_files}" ]]; then
    echo "SetUID:${unknown_setuid_files}"
    fatal "found files/directories with SetUID/GID bit set"
fi
ok "no unknown file/directory with SetUID/GID bit set"
